package com.example.tool.util;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class FileUtil {

    public static MultipartFile convert(String fileUrl, String fileName) throws IOException {
        URL url = new URL(fileUrl);
        try (InputStream inputStream = url.openStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            return new MockMultipartFile(
                    "file",
                    fileName,
                    null,
                    outputStream.toByteArray() // 使用字节数组而不是流
            );
        }
    }

    public static void main(String[] args) {
//        try {
//          String fileUrl = "https://alidocs.dingtalk.com/i/nodes/93NwLYZXWybly4ANUXjxNa7jVkyEqBQm";
//            String fileName = "fff.xlsx"; // 根据实际文件类型设置
//        try {
//            MultipartFile multipartFile = FileUtil.convert(fileUrl, fileName);
//
//            // 现在可以使用multipartFile了
//            System.out.println("文件名: " + multipartFile.getOriginalFilename());
//            System.out.println("文件大小: " + multipartFile.getSize() + " bytes");
//            List<LogisticsEntitiesDO> dataList = EasyExcel.read(multipartFile.getInputStream())
//                    .excelType(ExcelTypeEnum.XLSX)
//                    .sheet()
//                    .head(LogisticsEntitiesDO.class)
//                    .doReadSync();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String fileName = "temp.xlsx";
//
//        try {
//            // 下载文件到本地临时文件
//            FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
//
//            // 读取Excel
//            List<ZopTemplateBean> dataList = EasyExcel.read(fileName)
//                    .head(ZopTemplateBean.class)
//                    .sheet()
//                    .doReadSync();
//       System.out.println(dataList);
//            // 处理完成后删除临时文件
//            new File(fileName).delete();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

    }
}
